package helpers

import (
	"crypto/tls"
	"encoding/json"
	"fmt"
	"net/http"
	"time"

	"github.com/f5devcentral/f5-bigip-rest-go/utils"
)

// connection test helper for connection test.
type ConnectHelper struct {
	Client *http.Client
}

func NewConnectHelper() *ConnectHelper {
	return &ConnectHelper{
		Client: &http.Client{
			Transport: &http.Transport{
				TLSClientConfig: &tls.Config{
					InsecureSkipVerify: true,
				},
			},
			Timeout: 60 * time.Second,
		},
	}
}

func (ch *ConnectHelper) GetJson(url string) (map[string]interface{}, error) {
	headers := map[string]string{
		"Content-Type": "application/json",
	}
	code, b, err := utils.HttpRequest(ch.Client, url, "GET", "", headers)
	if err != nil {
		return nil, err
	} else if code != 200 {
		return nil, fmt.Errorf("non-200 response: %s", b)
	} else {
		var rlt map[string]interface{}
		err = json.Unmarshal(b, &rlt)
		if err != nil {
			return nil, fmt.Errorf("failed to unmarshal response: %s", err.Error())
		} else {
			return rlt, nil
		}
	}
}

func (ch *ConnectHelper) Get(url string) (int, []byte, error) {
	return utils.HttpRequest(ch.Client, url, "GET", "", nil)
}
